package com.cloud.bc.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cloud.bc.model.domain.UserInfo;
import com.cloud.bc.model.entity.*;
import com.cloud.bc.model.enums.CookieConst;
import com.cloud.bc.model.request.DistrictConvertRequest;
import com.cloud.bc.model.request.SingleListRequest;
import com.cloud.bc.model.request.VoiceListRequest;
import com.cloud.bc.service.*;
import com.cloud.common.util.CookieUtils;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

@AllArgsConstructor
@Controller
@RequestMapping("m/single")
public class SingleController extends BaseController {

    private final BcSinglesService bcSinglesService;
    private final BcSingleContactsService bcSingleContactsService;
    private final BcSingleMatesService bcSingleMatesService;
    private final BcUsersService bcUsersService;
    private final BcLikesService bcLikesService;
    private final BcFootprintsService bcFootprintsService;
    //申请表
    private final BcContacapplysService bcContacapplysService;
    private final BcUserPhotosService bcUserPhotosService;
    private final BcCategorysService bcCategorysService;
    private final BcCategoryDistrictsService bcCategoryDistrictsService;

    @SneakyThrows
    @GetMapping("search")
    public void list(HttpServletRequest request, HttpServletResponse response,
                     String userId
    ) {
        //判断userId是否存在
//        存在跳详情，不存在跳列表
        Integer numUserId = Convert.toInt(userId, 0);
        boolean isList = true;
        if (numUserId > 0) {
            //查询单身详情是否存在
            BcSingles bcSingles = bcSinglesService.selectOne(new BcSingles().setUserId(numUserId));
            if (null != bcSingles && Convert.toInt(bcSingles.getUserId()) > 0) {
                response.sendRedirect("/m/single/info/" + numUserId);
                isList = false;
            }
        }
        //跳转到列表
        if (isList) {
            response.sendRedirect("/m/single/list?userId=" + userId);
        }
    }

    @GetMapping("list")
    public ModelAndView list(HttpServletRequest request, HttpServletResponse response,
                             SingleListRequest reqParam
    ) {
        ModelAndView view = baseView(request, "寻觅", "/m/single/list");
        //查询所有属性
        convertListReqParam(reqParam);
//        bcCategorysService.selectByIds()
        view.addObject("reqParam", reqParam);
        return view;
    }

    private void convertListReqParam(SingleListRequest reqParam) {
        //属性
        if (Convert.toInt(reqParam.getIncome(), 0) > 0) {
            BcCategorys bcCategorys = bcCategorysService.selectByCacheId(reqParam.getIncome());
            reqParam.setIncomeCn(bcCategorys.getName());
        }
        if (Convert.toInt(reqParam.getEducation(), 0) > 0) {
            BcCategorys bcCategorys = bcCategorysService.selectByCacheId(reqParam.getEducation());
            reqParam.setEducationCn(bcCategorys.getName());
        }
        if (Convert.toInt(reqParam.getMarriage(), 0) > 0) {
            BcCategorys bcCategorys = bcCategorysService.selectByCacheId(reqParam.getMarriage());
            reqParam.setMarriageCn(bcCategorys.getName());
        }
        if (Convert.toInt(reqParam.getChildren(), 0) > 0) {
            BcCategorys bcCategorys = bcCategorysService.selectByCacheId(reqParam.getChildren());
            reqParam.setChildrenCn(bcCategorys.getName());
        }
        if (Convert.toInt(reqParam.getConstellation(), 0) > 0) {
            BcCategorys bcCategorys = bcCategorysService.getCategoryById("constellation", reqParam.getConstellation());
            reqParam.setConstellationCn(bcCategorys.getName());
        }
        if (Convert.toInt(reqParam.getMarry(), 0) > 0) {
            BcCategorys bcCategorys = bcCategorysService.selectByCacheId(reqParam.getMarry());
            reqParam.setMarryCn(bcCategorys.getName());
        }
        if (Convert.toInt(reqParam.getIndustry(), 0) > 0) {
            BcCategorys bcCategorys = bcCategorysService.selectByCacheId(reqParam.getIndustry());
            reqParam.setIndustryCn(bcCategorys.getName());
        }
        if (Convert.toInt(reqParam.getHouse(), 0) > 0) {
            BcCategorys bcCategorys = bcCategorysService.selectByCacheId(reqParam.getHouse());
            reqParam.setHouseCn(bcCategorys.getName());
        }
        if (Convert.toInt(reqParam.getReligious(), 0) > 0) {
            BcCategorys bcCategorys = bcCategorysService.selectByCacheId(reqParam.getReligious());
            reqParam.setReligiousCn(bcCategorys.getName());
        }
        if (Convert.toInt(reqParam.getNationality(), 0) > 0) {
            BcCategorys bcCategorys = bcCategorysService.selectByCacheId(reqParam.getNationality());
            reqParam.setNationalityCn(bcCategorys.getName());
        }
        if (Convert.toInt(reqParam.getCar(), 0) > 0) {
            BcCategorys bcCategorys = bcCategorysService.selectByCacheId(reqParam.getCar());
            reqParam.setCarCn(bcCategorys.getName());
        }
        if (Convert.toInt(reqParam.getFamilyBackg(), 0) > 0) {
            BcCategorys bcCategorys = bcCategorysService.selectByCacheId(reqParam.getFamilyBackg());
            reqParam.setFamilyBackgCn(bcCategorys.getName());
        }
        //回写属性
        //回写区域
        DistrictConvertRequest districtConvertRequest = new DistrictConvertRequest();
        districtConvertRequest.setDistrict(reqParam.getDistrict());
        bcCategoryDistrictsService.getCityConvert(districtConvertRequest);
        BeanUtil.copyProperties(districtConvertRequest, reqParam);
        //区域
    }

    /**
     * 单身详情
     */
    @GetMapping("info/{id}")
    public ModelAndView info(HttpServletRequest request, HttpServletResponse response,
                             @PathVariable("id") Integer id) throws IOException {
        ModelAndView view = baseView(request, "单身详情", "m/single/info");
        BcSingles bcSingles = bcSinglesService.selectOne(new BcSingles().setUserId(id));
        if (null == bcSingles || Convert.toInt(bcSingles.getUserId(), 0) == 0) {
            response.sendRedirect("/m/home");
        }
        UserInfo userInfo = bcUsersService.getUserInfo(request);
        //如果当前用户有登录，就记录一下足迹
        setLoginSingle(userInfo, id);
        bcSingles.setAge(bcSinglesService.ageConvert(bcSingles.getBirthday()));
        //如果头象审核没通过就给赋值为空
        Integer photoCheck = Convert.toInt(bcSingles.getPhotoCheck(), 0);
        if (photoCheck != 1) {
            bcSingles.setPhoto("");
        }
        //联系方式
        BcSingleContacts bcSingleContacts = bcSingleContactsService.selectOne(new BcSingleContacts().setUserId(id));
        bcSingleContacts = bcSingleContacts == null ? new BcSingleContacts() : bcSingleContacts;
        //查询联系方式状态
        int showHoldContact = isShowHoldContact(id, userInfo);
        //择偶标准
        BcSingleMates bcSingleMates = bcSingleMatesService.selectOne(new BcSingleMates().setUserId(id));
        bcSingleMates = bcSingleMates == null ? new BcSingleMates() : bcSingleMates;
//        判断当前用户是否VIP，只有VIP才会显示相册，声音，视频
        boolean isVip = bcSinglesService.isVip(userInfo);
        //查询相册,只要审核通过的图片
        IPage<BcUserPhotos> bcUserPhotosIPage = bcUserPhotosService.selectPage(new Page(1, 20),
                new BcUserPhotos().setUserId(id).setIsCheck(1));
        view.addObject("eid", setEid(request, response, id));
        view.addObject("single", bcSingles);
        view.addObject("bcSingleContacts", bcSingleContacts);
        view.addObject("bcSingleMates", bcSingleMates);
        view.addObject("isLike", isLike(id, userInfo));
        view.addObject("showHoldContact", showHoldContact);
        view.addObject("isVip", isVip);
        view.addObject("getUserPhotoData", getUserPhotoData(bcUserPhotosIPage.getRecords()));
        view.addObject("photoSize", bcUserPhotosIPage.getRecords() == null ? 0 : bcUserPhotosIPage.getRecords().size());
        //增加浏览量
        bcSinglesService.updateBrowse(id);
        return view;
    }

    //设置推荐地址
    private String setEid(HttpServletRequest request,
                          HttpServletResponse response,
                          Integer id) {
        String eid = request.getParameter("eid");
        if (!StrUtil.isEmpty(eid)) {
            //如果获取到的地址里包括推荐人，就存到cookie里
            CookieUtils.setCookie(request, response, CookieConst.eidCookie, eid);
        }
        UserInfo userInfo = bcUsersService.getUserInfo(request);
//        http://jiaoyou.xiats.com/single/info/41
        String url = config.getWebSite() + "m/single/info/" + id;
        if (userInfo == null) {
            return url;
        }
        String eidEncode = bcSinglesService.getEidEncode(userInfo.getId() + "");
        url += "?eid=" + eidEncode;
        return url;
    }

    private String getUserPhotoData(List<BcUserPhotos> list) {
        if (null == list || list.size() <= 0) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        for (BcUserPhotos item : list) {
            sb.append("<li class=\"item\" >");
            sb.append("<img photo_mode=\"1\"");
            sb.append(" max-src='" + item.getPhoto() + "_2000x2000.jpg'");
            sb.append(" bc-lazy-img='" + item.getPhoto() + "_200x200.jpg'");
            sb.append(" src='" + item.getPhoto() + "_200x200.jpg'");
            sb.append("</li>");
        }
        return sb.toString();
    }

    /**
     * 查询申请中是否有数据
     */
    private int isShowHoldContact(int userId, UserInfo userinfo) {
        if (null == userinfo || Convert.toInt(userinfo.getId(), 0) <= 0) {
            return 0;
        }
        BcContacapplys bcContacapplys = new BcContacapplys();
        bcContacapplys.setUserId(userinfo.getId());
        bcContacapplys.setTargetId(userId);
        bcContacapplys.setAgree(3);
        int count = bcContacapplysService.count(bcContacapplys);
        if (count > 0) {
            return 1;
        }
        return 0;
    }

    /**
     * 判断是否是我喜欢
     */
    private int isLike(int userId, UserInfo userInfo) {
        if (null == userInfo || Convert.toInt(userInfo.getId(), 0) == 0) {
            return 0;
        }
        BcLikes bcLikes = new BcLikes();
        bcLikes.setTargetId(userId);
        bcLikes.setUserId(userInfo.getId());
        int count = bcLikesService.count(bcLikes);
        if (count > 0) {
            return 1;
        }
        return 0;
    }

    /**
     * 判断足迹
     */
    private void setLoginSingle(UserInfo userInfo, Integer id) {
        if (null == userInfo || Convert.toInt(userInfo.getId(), 0) == 0) {
            return;
        }
        if (userInfo.getId() != id) {
            //设置足迹,但不能是自己
            BcFootprints bcFootprints = new BcFootprints();
            bcFootprints.setUserId(userInfo.getId());
            int count = bcFootprintsService.count(bcFootprints);
            if (count > 0) {
                return;
            }
            bcFootprints.setTargetId(id);
            bcFootprintsService.save(bcFootprints);
            //设置足迹结束
        }
    }

}
